package leetcode.list;

/**
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 *
 * @author mazouri
 * @create 2021-08-18 17:57
 */
public class _19_removeNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }

        ListNode node = head;

        //求出链表长度
        int size = 0;
        while (node != null) {
            size++;
            node = node.next;
        }

        //如果当前链表只有一个元素，直接返回null即可；如果删除第一个元素，直接返回head的下一个结点
        if (size - n == 0) {
            return head.next;
        }

        node = head;
        for (int i = 0; i < size - n - 1; i++) {
            node = node.next;
        }

        node.next = node.next.next;
        return head;
    }
}
